#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import psutil
import time
import threading
from flask import Flask, jsonify
from flask_cors import CORS

# 系统监控信息类
class SystemMonitorInfo:
    def __init__(self):
        self.overloaded = False
        self.cpu_usage = 0.0
        self.memory_usage = 0.0
        self.last_check_time = 0
        self.threshold = 80.0

# 站点配置信息类
class SiteConfig:
    def __init__(self):
        self.main_site = "https://2025.task2030.xyz/"
        self.backup_site = "https://zjnh.yamhk.top/"

# 全局变量
monitor_info = SystemMonitorInfo()
site_config = SiteConfig()
system_overloaded = False

# 检查系统资源使用情况
def check_system_resources():
    global system_overloaded, monitor_info
    
    try:
        # 获取CPU使用率
        cpu_percent = psutil.cpu_percent(interval=1)
        
        # 获取内存信息
        memory_info = psutil.virtual_memory()
        
        # 更新监控信息
        monitor_info.cpu_usage = cpu_percent
        monitor_info.memory_usage = memory_info.percent
        monitor_info.last_check_time = int(time.time() * 1000)
        
        # 检查是否超过阈值
        if monitor_info.cpu_usage >= monitor_info.threshold or monitor_info.memory_usage >= monitor_info.threshold:
            if not system_overloaded:
                system_overloaded = True
                monitor_info.overloaded = True
                print("系统满载警告: CPU使用率={:.2f}%，内存使用率={:.2f}%，已暂停服务".format(monitor_info.cpu_usage, monitor_info.memory_usage))
        else:
            if system_overloaded:
                system_overloaded = False
                monitor_info.overloaded = False
                print("系统恢复正常: CPU使用率={:.2f}%，内存使用率={:.2f}%，已恢复服务".format(monitor_info.cpu_usage, monitor_info.memory_usage))
                
    except Exception as e:
        print("检查系统资源时发生错误: {}".format(e))

# 启动定时监控
def start_monitoring():
    def monitor_loop():
        # 立即执行一次检查
        check_system_resources()
        
        # 启动定时任务，每5秒检查一次
        while True:
            time.sleep(5)
            check_system_resources()
    
    # 在单独的线程中运行监控循环
    monitor_thread = threading.Thread(target=monitor_loop)
    monitor_thread.daemon = True
    monitor_thread.start()

# 创建Flask应用
app = Flask(__name__)
CORS(app)  # 启用CORS

# API路由

# 获取系统监控信息
@app.route('/api/monitor-info', methods=['GET'])
def get_monitor_info():
    return jsonify({
        "code": 200,
        "data": {
            "overloaded": monitor_info.overloaded,
            "cpuUsage": monitor_info.cpu_usage,
            "memoryUsage": monitor_info.memory_usage,
            "lastCheckTime": monitor_info.last_check_time,
            "threshold": monitor_info.threshold
        },
        "message": "success"
    })

# 获取站点配置信息
@app.route('/api/site-config', methods=['GET'])
def get_site_config():
    return jsonify({
        "code": 200,
        "data": {
            "mainSite": site_config.main_site,
            "backupSite": site_config.backup_site
        },
        "message": "success"
    })

if __name__ == '__main__':
    # 启动系统监控
    start_monitoring()
    
    # 启动服务器
    print("服务器监控服务已启动，监听端口: 55055")
    app.run(host='0.0.0.0', port=55055, debug=False)